package br.com.financas.controller.converter;

import java.util.Map;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import br.com.base.model.Entidade;

/**
 * 
 * @author milton
 *
 */
@FacesConverter(value = "entidadeConverter")
public class EntidadeConverter implements Converter {

	@SuppressWarnings("rawtypes")
	protected void addAttribute(final UIComponent component, final Entidade o) {
		String key = "";
		key = o.toString();
		this.getAttributesFrom(component).put(key, o);
	}

	@Override
	public Object getAsObject(final FacesContext context, final UIComponent component, final String value) {
		if (value != null) { return this.getAttributesFrom(component).get(value); }
		return null;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public String getAsString(final FacesContext context, final UIComponent component, final Object value) {
		String strValue = null;
		if ((value != null) && !"".equals(value)) {
			Entidade entity = (Entidade) value;
			this.addAttribute(component, entity);

			String codigo = entity.toString();
			if (codigo != null) { return String.valueOf(codigo); }
		}

		return strValue;
	}

	protected Map<String, Object> getAttributesFrom(final UIComponent component) {
		return component.getAttributes();
	}


}
